package com.alinesno.cloud.base.storage.utils;

import java.io.IOException;
import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alinesno.cloud.base.storage.config.StorageQiuniuConfig;
import com.alinesno.cloud.common.facade.orm.id.SnowflakeIdWorker;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * 七牛数据存储方案
 *
 * @author WeiXiaoJin
 * @since 2018年2月23日 下午2:37:04
 */
@SuppressWarnings("deprecation")
@Component
public class QiniuStoreHandler {

	//日志记录
	private final static Logger logger = LoggerFactory.getLogger(QiniuStoreHandler.class);

	@Autowired
	private StorageQiuniuConfig qiuniuConfig ; 

	private  Gson gson = new Gson() ;

	/**
	 * 普通上传
	 * @param localFilePath
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public  String upload(String localFilePath) throws IOException {

		Configuration cfg = new Configuration(getZone(qiuniuConfig.getSpaceZone()));
		UploadManager uploadManager = new UploadManager(cfg);

		Auth auth = Auth.create(qiuniuConfig.getAccessKey(), qiuniuConfig.getSecretKey()) ;
		String key = SnowflakeIdWorker.getId()+"" ;
		String upToken = auth.uploadToken(qiuniuConfig.getSpaceBucket());

		try {
			
			Response response = uploadManager.put(localFilePath, key, upToken);
			DefaultPutRet putRet = gson.fromJson(response.bodyString(), DefaultPutRet.class);

			logger.debug("put key = {} , hash = {}" , putRet.key , putRet.hash);
		} catch (QiniuException ex) {
			Response r = ex.response;
			try {
				logger.debug(r.bodyString());
			} catch (QiniuException ex2) {
				logger.error("上传文件错误:",ex2);
			}
			return null ;
		}
		String domain = qiuniuConfig.getHostDomain() ; 
		return  (domain.endsWith("/")?domain:domain+"/")+key ;
	}

	/**
	 * 获取到区域
	 * @param zone2
	 * @return
	 */
	private  Zone getZone(String zone) {
		Zone z = Zone.zoneNa0() ;  //北美
		if(StringUtils.isNotBlank(zone)) {
			if(zone.equals("0")) {
				z = Zone.zone0() ;
			}else  if(zone.equals("1")) {
				z = Zone.zone1() ;
			}else  if(zone.equals("2")) {
				z = Zone.zone2() ;
			}
		}
		return z ;
	}

	/**
	 * 获取私有下载链接
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public  String privateUrl(String fileName) throws IOException {

		String encodedFileName = URLEncoder.encode(fileName, "utf-8");
		String publicUrl = String.format("%s/%s", qiuniuConfig.getHostDomain(), encodedFileName);

		long expireInSeconds = Integer.parseInt(qiuniuConfig.getHostDomainDeadline()) ;//以秒为单位
		Auth auth = Auth.create(qiuniuConfig.getAccessKey(), qiuniuConfig.getSecretKey());
		String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);

		return finalUrl ;
	}

	/**
	 * 根据id删除文件
	 * @param fileId
	 * @return
	 */
	public boolean deleteData(String fileId) {
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(this.getZone(qiuniuConfig.getSpaceZone()));
		Auth auth = Auth.create(qiuniuConfig.getAccessKey(), qiuniuConfig.getSecretKey());
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
		    bucketManager.delete(qiuniuConfig.getSpaceBucket(), fileId);
		} catch (QiniuException ex) {
		    logger.error("code = {} , response = {}" , ex.code() , ex.response.toString());
		    return false;
		}
		return true;
	}

}